package com.zhangtai.modules.controller.member;

import com.alibaba.fastjson.JSONObject;
import com.zhangtai.exception.RException;
import com.zhangtai.modules.controller.admin.CommonController;
import com.zhangtai.modules.controller.admin.PromotionController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dto.PromotionDto;
import com.zhangtai.modules.dto.PromotionEntityDto;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.PromotionEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.promotion.PromotionService;
import com.zhangtai.modules.vo.PromotionListVo;
import com.zhangtai.modules.vo.PromotionVo;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("promotion")
@Slf4j
@Api(tags="员工自助晋升")
@RestController()
public class PromotionMemberController {

    @Autowired
    private PromotionService promotionService;
    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;
    @Autowired
    private MemberLoginController memberLoginController ;
    @Autowired
    private PromotionController promotionController;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private CommonController commonController;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @PostMapping("/getMemberPromotionList")
    @ApiOperation("获取自助端员工晋升列表")
    public R<PageResult<PromotionDto>> getMemberPromotionList(@RequestBody @Valid PromotionListVo promotionListVo, HttpServletRequest request)throws  Exception{
//        List<Long> jobIds = new ArrayList<>();
//        List<Long>  jobSystemIds = new ArrayList<>();
//        //体系
//        if(!StringUtil.isNullOrEmpty(promotionListVo.getJobSystem())){
//            jobSystemIds = baseMssqlService.findSystemIdByName(promotionListVo.getJobSystem());
//        }
//        //职位
//        if(!StringUtil.isNullOrEmpty(promotionListVo.getJob())){
//            jobIds = baseMssqlService.findJobIdByJobName(promotionListVo.getJob());
//        }
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        Long orgId = userInfo.getLong("depId");
        List<Long> orgIds = new ArrayList<>();
        orgIds.add(orgId);
        PageResult<PromotionEntityDto> result =promotionService.queryPage(promotionListVo.getPromotionType(),userInfo.getString("usercode"),
                promotionListVo.getName(),promotionListVo.getOrgName(),promotionListVo.getDepartmentName(),
                promotionListVo.getExpeditionStatus(),promotionListVo.getIsDistribute(),orgIds,promotionListVo.getPromotionKind(),
                1,promotionListVo.getPageNum(),promotionListVo.getPageSize(),promotionListVo.getStatus());
        List<PromotionEntityDto> promotionEntities = result.getList();
        List<PromotionDto> dtoList = promotionController.getPromotionDtoList(promotionEntities);
        PageResult<PromotionDto> re = new PageResult<>();



            re.setList(dtoList);


        re.setCurrPage(result.getCurrPage());
        re.setPageSize(result.getPageSize());
        re.setTotalCount(result.getTotalCount());
        re.setTotalPage(result.getTotalPage());

        return R.ok(re);
    }

    @PostMapping("/saveOrUpdatePromotion")
    @ApiOperation("保存/更新晋升信息")
    @Transactional
    public R saveOrUpdatePromotion(HttpServletRequest request,@RequestBody @Valid PromotionVo promotionVo)throws  Exception{
        PromotionEntity promotionEntity = BeanUtilsMabach.doToDto(promotionVo, PromotionEntity.class);
        JSONObject userInfo = memberLoginController.getUserInfo(request).getData();
        String applyUserCode = userInfo.getString("usercode");
        if (StringUtils.isEmpty(applyUserCode)) {
            throw new RException("请先登录");
        }
        Long oid = userInfo.getLong("id");
        String name = userInfo.getString("name");
        Long depId = userInfo.getLong("depId");
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectById(oid);
        if(employeeInfoEntity==null){
            employeeInfoEntity = baseMssqlService.finEmpFromMssqlByCode(applyUserCode);
        }
        //填充员工当前工作信息
        Date date = new Date();
        promotionEntity.setOid(oid);
        promotionEntity.setName(name);
        promotionEntity.setCode(applyUserCode);
        promotionEntity.setBeforeUnitId(employeeInfoEntity.getUnitId());
        promotionEntity.setCreateTime(date);
        promotionEntity.setBeforeOrgId(employeeInfoEntity.getOrgId());
        promotionEntity.setBeforeJobId(employeeInfoEntity.getJobId());
        promotionEntity.setBeforeJobLevelId(employeeInfoEntity.getJobLevelId());
        promotionEntity.setIsSelf(1);
        promotionEntity.setBeforeUnitId(depId);

        promotionEntity.setBeginExpeditionDate(promotionVo.getPromotionDate());
        promotionEntity.setBeforeJobType(employeeInfoEntity.getJobLevelType().toString());
        if(promotionVo.getPromotionType()!=1){
            Date endDate = DateUtils.addDateMonths(promotionVo.getPromotionDate(),promotionVo.getProbationday());
            promotionEntity.setEndExpeditionDate(endDate);
            promotionEntity.setExpeditionDays(promotionVo.getProbationday());
        }
        promotionEntity.setApplierCode(applyUserCode);
        promotionEntity.setApplier(name);

        String fileUrl = null;
        if(!CollectionUtils.isEmpty(promotionVo.getFileUrl())){
            fileUrl = commonController.getFileUrls(promotionVo.getFileUrl(),oid,"晋升附件");
        }
        promotionEntity.setFileUrl(fileUrl);
        //审批待发起
        promotionEntity.setStatus(1);
        if(ObjectUtils.isEmpty(promotionEntity.getPromotionId())){
            promotionEntity.setPromotionId(snowflakeIdWorker.nextId());
            promotionService.saveE(promotionEntity);
        }else{
            promotionService.updateByIdE(promotionEntity);
        }
        return R.ok();
    }

    @DeleteMapping("/deletePromotion")
    @ApiOperation("删除晋升信息")
    @Transactional
    public R deletePromotion(String id){
        if(StringUtils.isEmpty(id)){
            return R.error("晋升id不存在！");
        }
        promotionService.removeOneById(Long.parseLong(id));
        return R.ok();
    }
}
